﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace Galaktika.BI.Silverlight.ClientApp
{
    using Galaktika.BI.Runtime;
    using Galaktika.BI.Runtime.Services;
    using Galaktika.BI.Extensibility;
    using Galaktika.BI.Extensibility.Dom;
    using Galaktika.BI.Extensibility.Dom.Workstation;
    using Galaktika.BI.Silverlight.Controls;
    using Galaktika.BI.Silverlight.ClientApp.Items;
    using Galaktika.BI.Silverlight.ClientApp.Services;
    using System.Windows.Controls.Primitives;
    using System.Windows.Browser;
    using Galaktika.BI.Silverlight.Services;
    using Galaktika.BI.Silverlight.Controls.PivotGrid;
    using Ranet.Olap.Core.Data;
    using System.Net.NetworkInformation;
    using Galaktika.BI.Silverlight.Commands;
    using Galaktika.BI.Silverlight.ClientApp.View;

    public partial class Page : UserControl, IFormContainer
    {
        private const string Images = "/Galaktika.BI.ImageLibrary;component/";
        private const string Images1 = "/Galaktika.BI.Silverlight.ClientApp;component/";
        private const string PrintImage = "Print.png";

        private ToggleButton btn_Menu, btn_Wrap, btn_RunningOnly, btn_CO, btn_Vars;
        private Button btn_Back, btn_Forward, btn_Refresh, btn_Reset, btnRun, mnu_Back, mnu_Forward,
            btnClear, btnCopy, btnFullscreen,
            btn_Help, btn_Settings, btn_Print;
        private GridSplitter mainSpl;
        private VerticalExpander menuExpander;

        public Page()
        {
            InitializeComponent();

            #region Creation
            btn_Menu = new ToggleButton();
            btn_Back = new Button();
            btn_Forward = new Button();
            btn_Refresh = new Button();
            btn_Reset = new Button();
            btnRun = new Button();
            btnFullscreen = new Button();
            mnu_Back = new Button();
            mnu_Forward = new Button();
            menuExpander = new VerticalExpander();
            menuExpander.HeaderWidth = new GridLength(0);
            btnClear = new Button();
            btnCopy = new Button();
            btn_Wrap = new ToggleButton();
            btn_RunningOnly = new ToggleButton();
            btn_Help = new Button();
            btn_CO = new ToggleButton();
            btn_Vars = new ToggleButton();
            btn_Print = new Button();
            btn_Settings = new Button();

            BitmapImage bmpBack = new BitmapImage(new Uri(Images + "Indicators/x16/Back.png", UriKind.Relative));
            Image imgBack = new Image();
            imgBack.Source = bmpBack;
            this.btn_Back.Content = imgBack;

            btn_Back.Height = 26;
            btn_Back.Width = 26;
            btn_Back.Margin = new Thickness(1, 1, 1, 1);

            BitmapImage bmpForward = new BitmapImage(new Uri(Images + "Indicators/x16/Forward.png", UriKind.Relative));
            Image imgForward = new Image();
            imgForward.Source = bmpForward;
            this.btn_Forward.Content = imgForward;

            btn_Forward.Height = 26;
            btn_Forward.Width = 26;
            btn_Forward.Margin = new Thickness(1, 1, 1, 1);

            PageNavigator pn = new PageNavigator(TabContainer.TabControl, App.CurrentApp.Binder, this.btn_Back, this.btn_Forward, this.mnu_Back, this.mnu_Forward, btn_Refresh, btn_Reset, btnRun, btnFullscreen, btn_CO, btn_Vars);
            this.Navigator = pn;
            this.AppManager = pn;
            this.TabPageFormResolver = pn;

            ToolTipService.SetToolTip(btn_Back, new StyledToolTip() { Content = Localization.Str_Back });
            ToolTipService.SetToolTip(btn_Forward, new StyledToolTip() { Content = Localization.Str_Forward });
            ToolTipService.SetToolTip(btn_Menu, new StyledToolTip() { Content = Localization.Str_ShowHideWorkstationTree });
            ToolTipService.SetToolTip(btn_Refresh, new StyledToolTip() { Content = Localization.Str_Refresh });
            ToolTipService.SetToolTip(btn_Reset, new StyledToolTip() { Content = Localization.Str_Reset });
            ToolTipService.SetToolTip(btnRun, new StyledToolTip() { Content = Localization.Str_RunPendingChanges });
            ToolTipService.SetToolTip(btnFullscreen, new StyledToolTip() { Content = Localization.Tooltip_ViewInFullScreenMode });
            ToolTipService.SetToolTip(btn_Help, new StyledToolTip() { Content = Localization.Tooltip_Help });
            ToolTipService.SetToolTip(btn_CO, new StyledToolTip() { Content = Localization.Tooltip_ContextWindows });
            ToolTipService.SetToolTip(btn_Settings, new StyledToolTip() { Content = Localization.Tooltip_Settings });
            ToolTipService.SetToolTip(btn_Print, new StyledToolTip() { Content = Localization.Tooltip_Print });
            ToolTipService.SetToolTip(btn_Vars, new StyledToolTip() { Content = Localization.Tooltip_Variables });

            #endregion

            App.CurrentApp.AddService(typeof(IUserTaskManager), new UserTaskManager(outputControl.TaskPanel, txtStatus));
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
            StatusBarManager.Bar = pbarProcess;
            StatusBarManager.Dispatcher = pbarProcess.Dispatcher;
        }

        public string CardId { get; private set; }
        private IDictionary<string, string> m_Params;
        public Page(string cardId, IDictionary<string, string> parameters)
            : this()
        {
            this.CardId = cardId;
            m_Params = parameters;
        }

        TreeView m_ArmTreeView;
        private void CreateWorkstations()
        {
            if (m_Workstations != null && m_ArmTreeView != null)
            {
                List<BrickObject> list = new List<BrickObject>(m_Workstations.Count);
                m_Workstations.ForEach(ws => list.Add(ws));
                this.PopulateMenuCore(m_ArmTreeView.Items, list);
                if (m_ArmTreeView != null)
                {
                    menuExpander.Content = m_ArmTreeView;
                    menuExpander.IsExpanded = true;
                }
                m_Workstations = null;
                m_ArmTreeView = null;
            }
        }

        public UserControl RootControl
        {
            get
            {
                return this;
            }
        }

        public ContentControl ContentHolder
        {
            get
            {
                return contentHolder;
            }
        }

        public IFormNavigator Navigator { get; private set; }
        public IAppManager AppManager { get; private set; }
        public ITabPageFormResolver TabPageFormResolver { get; private set; }

        private Button ButtonBack
        {
            get { return this.btn_Back; }
        }

        private Button ButtonForward
        {
            get { return this.btn_Forward; }
        }

        public Button RunImmediate
        {
            get
            {
                return btnRun;
            }
        }

        private List<BrickWorkstation> m_Workstations;
        public void Initialize(List<BrickWorkstation> workstations)
        {
            m_Workstations = workstations;
            this.CreateWorkstations();
            App.CurrentApp.Binder.Initialize(null);
            this.AppManager.UpdateCurrentContext();

            if (!string.IsNullOrEmpty(this.CardId))
            {
                btn_Menu.IsChecked = true;

                var vars = this.ExtractVariables(true);
                vars.Add("formId", this.CardId);
                vars.Add("openInNewWindow", bool.TrueString);
                this.Navigator.NavigateTo(vars);//this.CardId, true, false);
            }
            else
            {
                string formId = ClientResources.GetGlobalValue("_$StartupFormId");
                if (!String.IsNullOrEmpty(formId))
                {
                    this.Navigator.NavigateTo(formId, true, true);
                }
            }
        }

        private IDictionary<string, string> ExtractVariables(bool modifyDefaults)
        {
            var res = new SafeDictionary<string, string>();
            if (m_Params.Count > 0)
            {
                var variables = App.CurrentApp.Binder.DefaultVariables;
                foreach (var kv in m_Params)
                {
                    if (string.IsNullOrEmpty(kv.Value)) continue;
                    if (variables.IsExists(kv.Key) && !res.ContainsKey(kv.Key))
                    {
                        var value = Uri.UnescapeDataString(kv.Value);
                        variables[kv.Key].DefaultValue = value;
                        res.Add(kv.Key, value);
                    }
                }
            }

            return res;
        }

        void btn_RunningOnly_Click(object sender, RoutedEventArgs e)
        {
            outputControl.TaskPanel.SetFilter(!btn_RunningOnly.IsChecked.Value);
        }

        void btnFullscreen_Click(object sender, RoutedEventArgs e)
        {
            //IAppManager app = App.CurrentApp.GetService<IAppManager>();
            //if (app.CurrentForm != null)
            //{
            //    FormView fv = app.CurrentForm as FormView;
            //    if (fv != null)
            //    {
            //        FullScreenSwitcher.ShowInFullScreen(fv.Layout);
            //    }
            //}
            FullScreenSwitcher.Switch();
            if (FullScreenSwitcher.IsFullScreen)
            {
                ToolTipService.SetToolTip(btnFullscreen, new StyledToolTip() { Content = Localization.ToolTip_ExitFullscreenMode });
            }
            else
            {
                ToolTipService.SetToolTip(btnFullscreen, new StyledToolTip() { Content = Localization.Tooltip_ViewInFullScreenMode });
            }
        }

        void btnRun_Click(object sender, RoutedEventArgs e)
        {
            btn_Refresh_Click(sender, e);
            //IAppManager app = App.CurrentApp.GetService<IAppManager>();
            //if (app.CurrentForm != null)
            //{
            //    IBindingContext context = App.CurrentApp.Binder.GetContext((FrameworkElement)app.CurrentForm);

            //    if (context != null)
            //    {
            //        App.CurrentApp.Binder.RefreshImmediate(context);
            //    }
            //}
        }

        void TabOutputControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (btnCopy.IsEnabled && btn_Wrap.IsEnabled)
            {
                btnCopy.IsEnabled = false;
                btn_Wrap.IsEnabled = false;
                btn_RunningOnly.IsEnabled = true;
            }
            else
            {
                btnCopy.IsEnabled = true;
                btn_Wrap.IsEnabled = true;
                btn_RunningOnly.IsEnabled = false;
            }
        }

        void chkWrap_Unchecked(object sender, RoutedEventArgs e)
        {
            outputControl.TextBoxOutput.TextWrapping = TextWrapping.NoWrap;
        }

        void chkWrap_Checked(object sender, RoutedEventArgs e)
        {
            outputControl.TextBoxOutput.TextWrapping = TextWrapping.Wrap;
        }

        void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            outputControl.TextBoxOutput.SelectAll();

            if (outputControl.TextBoxOutput.SelectedText != null)
            {
                Clipboard.SetClipboardText(outputControl.TextBoxOutput.SelectedText);
            }
        }

        void btnClear_Click(object sender, RoutedEventArgs e)
        {
            outputControl.TextBoxOutput.Text = string.Empty;
            outputControl.TaskPanel.ClearTasks();
            outputControl.QueryViewer.ViewModel.Clear();
        }

        private void PopulateMenuCore(ItemCollection owner, List<BrickObject> items)
        {
            items.Sort((a, b) => Comparer<int>.Default.Compare(
                this.GetInsertIndex(a, owner),
                this.GetInsertIndex(b, owner)));
            foreach (BrickObject obj in items)
            {
                TreeViewItem item = new TreeViewItem();
                item.Style = App.Current.Resources["TreeViewItemGlowStyle"] as Style;
                item.Collapsed += new RoutedEventHandler(item_Collapsed);
                item.Expanded += new RoutedEventHandler(item_Expanded);

                ////item.MouseLeftButtonDown += new MouseButtonEventHandler(item_MouseLeftButtonDown);
                //item.IsTabStop = true;

                MainMenuHeader header = new MainMenuHeader();
                header.Cursor = Cursors.Hand;
                header.Text = obj.Title;

                //header.MouseDoubleClick += new MouseDoubleClickEventHandler(header_MouseDoubleClick);
                header.MouseLeftButtonUp += new MouseButtonEventHandler(header_MouseLeftButtonUp);
                header.Tag = obj;
                item.Header = header;

                if (!(obj is BrickContainer))
                {
                    if ((obj is BrickWorkstationItem) && (obj as BrickWorkstationItem).Image != null && (obj as BrickWorkstationItem).Image.Length > 0)
                    {
                        MemoryStream stream = new MemoryStream();
                        stream.Write((obj as BrickWorkstationItem).Image, 0, (obj as BrickWorkstationItem).Image.Length);
                        BitmapImage bi = new BitmapImage();
                        bi.SetSource(stream);
                        ((MainMenuHeader)item.Header).imgHeader.Source = bi;
                    }
                    else
                        ((MainMenuHeader)item.Header).imgHeader.Source =
                            new BitmapImage(new Uri(@"Images/Form.png", UriKind.Relative));
                }

                //owner.Insert(this.GetInsertIndex(obj, owner), item);
                owner.Add(item);
                string description = string.Empty;
                if (obj is BrickWorkstation)
                {
                    description = ((BrickWorkstation)obj).Description;
                }
                if (obj is BrickWorkstationItem)
                {
                    description = ((BrickWorkstationItem)obj).Description;
                }
                if (obj is BrickFolder)
                {
                    description = ((BrickFolder)obj).Description;
                }
                if (!string.IsNullOrEmpty(description) && obj.Title != description)
                {
                    ToolTipService.SetToolTip(header, new StyledToolTip() { Content = description });
                }
                else
                {
                    ToolTipService.SetToolTip(header, new StyledToolTip() { Content = obj.Title });
                }
                if (obj is BrickContainer)
                {
                    this.PopulateMenuCore(
                        item.Items,
                        ((BrickContainer)obj).Children);
                }
            }
        }

        void item_Expanded(object sender, RoutedEventArgs e)
        {
            if (((HeaderedItemsControl)sender).Items.Count != 0)
                ((MainMenuHeader)(((HeaderedItemsControl)sender).Header)).imgHeader.Source =
                    new BitmapImage(new Uri(@"Images/FolderOpen.png", UriKind.Relative));
            else
                ((MainMenuHeader)(((HeaderedItemsControl)sender).Header)).imgHeader.Source =
                    new BitmapImage(new Uri(@"Images/Form.png", UriKind.Relative));

        }

        void item_Collapsed(object sender, RoutedEventArgs e)
        {
            if (((HeaderedItemsControl)sender).Items.Count != 0)
                ((MainMenuHeader)(((HeaderedItemsControl)sender).Header)).imgHeader.Source =
                    new BitmapImage(new Uri(@"Images/Folder.png", UriKind.Relative));
            else
                ((MainMenuHeader)(((HeaderedItemsControl)sender).Header)).imgHeader.Source =
                    new BitmapImage(new Uri(@"Images/Form.png", UriKind.Relative));
        }

        void header_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            header_MouseDoubleClick(sender, e);
        }

        void header_MouseDoubleClick(object sender, EventArgs e)
        {
            MainMenuHeader header = sender as MainMenuHeader;
            if (header != null)
            {
                BrickWorkstationItem item = header.Tag as BrickWorkstationItem;
                if (item != null)
                {
                    if (item.ActionInvoker != null && item.ActionInvoker.Action != null)
                    {
                        IUserTaskManager taskManager = App.CurrentApp.GetService<IUserTaskManager>();
                        if (taskManager != null)
                        {
                            taskManager.RunTask(
                                string.Format(
                                    Localization.AppTask_ExecutingScript,
                                    item.ActionInvoker.Action.Name),
                                state => ScriptEngine.Execute(this, item.ActionInvoker));
                        }
                    }
                    else
                    {
                        IOutputService output = App.CurrentApp.GetService<IOutputService>();
                        if (output != null)
                        {
                            output.ShowWarning(Localization.Wrn_ActionInvokerIsNotSet);
                        }
                    }
                }
            }
        }

        private int GetInsertIndex(BrickObject insertingbrick, ItemCollection nodes)
        {
            if (insertingbrick != null)
            {
                return insertingbrick.NodeIndex;
            }

            return -1;
        }

        private int GetNodeIndexForItem(BrickObject nodeIndexerObject)
        {
            if (nodeIndexerObject != null)
            {
                return nodeIndexerObject.NodeIndex;
            }

            return -1;
        }

        private int GetIndexAfterLastNode(ItemCollection nodes)
        {
            return nodes.Count;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (this.rootContainer.RowDefinitions[1].Height.Value != 0.0)
            {
                this.rootContainer.RowDefinitions[1].Height = new GridLength(0.0);
            }
            else
            {
                this.rootContainer.RowDefinitions[1].Height = new GridLength(140.0);
            }
        }

        public TabControlOutput Output
        {
            get
            {
                return outputControl;
            }
        }

        private void btn_Back_Click(object sender, RoutedEventArgs e)
        {
            this.Navigator.GoBack();
        }

        private void btn_Forward_Click(object sender, RoutedEventArgs e)
        {
            this.Navigator.GoForward();
        }

        private void btn_Reset_Click(object sender, RoutedEventArgs e)
        {
            IAppManager app = App.CurrentApp.GetService<IAppManager>();
            if (app.CurrentForm != null)
            {
                IBindingContext context = App.CurrentApp.Binder.GetContext((FrameworkElement)app.CurrentForm);

                if (app.CurrentForm is FormView)
                    ResetContext(context, (FormView)app.CurrentForm);
            }
        }

        private void ResetContext(IBindingContext context, FormView form)
        {
            string formId = form.Id;

            string connectionName = this.FindConnection(form);
            if (!string.IsNullOrEmpty(connectionName))
            {
                this.RunUpdaterAction(
                    Localization.AppTask_RollbackChanges,
                    () => AnalysisTransactionManager.Rollback(context, connectionName));
            }

            var exe = App.CurrentApp.GetService<IExecutionContext>();
            if (exe != null)
            {
                App.CurrentApp.Binder.Reset(context);
                context.IsDirty = true;
                exe.DoDrillDown(context);
            }
        }

        private void RunUpdaterAction(string actionName, Action action)
        {
            string taskText = actionName;
            var taskMgr = App.CurrentApp.GetService<IUserTaskManager>();
            if (taskMgr != null)
            {
                taskMgr.RunTaskAsync(taskText,
                    state =>
                    {
                        try
                        {
                            action();
                        }
                        catch
                        {
                            // TODO: обработать
                        }
                        //ExecuteCommand(schema, context);
                    });
            }
        }

        private string FindConnection(FormView form)
        {
            string conn = this.FindConnection(form.Layout);
            if (!string.IsNullOrEmpty(conn))
            {
                return conn;
            }

            foreach (FormView ctxWin in form.ContextWindows)
            {
                conn = this.FindConnection(ctxWin.Layout);
                if (!string.IsNullOrEmpty(conn))
                {
                    return conn;
                }
            }

            return conn;
        }

        private string FindConnection(FrameworkElement control)
        {
            int childCount = VisualTreeHelper.GetChildrenCount(control);
            if (control is ScrollViewer && childCount == 0)
            {
                control = ((ScrollViewer)control).Content as FrameworkElement;
                childCount = VisualTreeHelper.GetChildrenCount(control);
            }
            for (int i = 0; i < childCount; i++)
            {
                FrameworkElement fe = VisualTreeHelper.GetChild(control, i) as FrameworkElement;
                if (fe == null) continue;

                if (fe is UpdateablePivotGridControlEx)
                {
                    CellSetData description = ((UpdateablePivotGridControlEx)fe).ADataSource as CellSetData;
                    if (description != null)
                    {
                        return description.Connection.ConnectionID;
                    }
                }
#warning Разрулить через общий интерфейс
                //if (fe is ChartControl)
                //{
                //    CellSetData description = ((ChartControl)fe).ADataSource as CellSetData;
                //    if (description != null)
                //    {
                //        return description.Connection.ConnectionID;
                //    }
                //}

                string conn = FindConnection(fe);
                if (!string.IsNullOrEmpty(conn))
                {
                    return conn;
                }
            }

            return string.Empty;
        }

        private static void ExecuteCommand(InvokeSchema schema, IBindingContext context)
        {
            using (var cmd = CommandDispatcher.Dispatch(schema))
            {
                cmd.Invoke();
                App.CurrentApp.Binder.RefreshImmediate(context);
            }
        }

        private void btn_Refresh_Click(object sender, RoutedEventArgs e)
        {
            IAppManager app = App.CurrentApp.GetService<IAppManager>();

            if (app.CurrentForm != null)
            {
                IBindingContext context = App.CurrentApp.Binder.GetContext((FrameworkElement)app.CurrentForm);
                if (context != null)
                {
                    context.Reset();
                    App.CurrentApp.Binder.RefreshImmediate(context);
                    app.UpdateCurrentContext();
                }
            }
        }

        private void btn_Menu_Checked(object sender, RoutedEventArgs e)
        {
            menuExpander.IsExpanded = false;
            mainSpl.Visibility = Visibility.Collapsed;
            Border border = TabContainer.TabControl.GetControlFromTemplate("Menu_Expander_Border") as Border;
            if (border != null)
            {
                border.Visibility = Visibility.Collapsed;
            }
            IncreaseQuota();
        }

        private void btn_Menu_Unchecked(object sender, RoutedEventArgs e)
        {
            menuExpander.IsExpanded = true;
            mainSpl.Visibility = Visibility.Visible;
            Border border = TabContainer.TabControl.GetControlFromTemplate("Menu_Expander_Border") as Border;
            if (border != null)
            {
                border.Visibility = Visibility.Visible;
            }
        }

        private static void IncreaseQuota()
        {
            try
            {
                long quota = IsolatedStorageFile.GetUserStoreForApplication().Quota;
                if (IsolatedStorageFile.GetUserStoreForApplication().AvailableFreeSpace < quota * 0.5)
                {
                    IsolatedStorageFile.GetUserStoreForApplication().IncreaseQuotaTo(quota * 2);
                }
            }
            catch (Exception exc)
            {
                var output = App.CurrentApp.GetService<IOutputService>();
                if (output != null)
                {
                    output.WriteLine(exc.Message);
                }
            }
        }

        private MainToolbarHolder m_MainToobar;
        public MainToolbarHolder MainToolbar
        {
            get
            {
                return m_MainToobar;
            }
        }

#warning Введено для целей отладки. Удалить.
        private static void SafeDoInit(Action a, string wassapMessage)
        {
            if (a == null) return;
            try
            {
                a();
            }
            catch
            {
                MessageBox.Show(wassapMessage);
                throw;
            }
        }

        private void LayoutRoot_LayoutUpdated(object sender, EventArgs e)
        {
            this.LayoutRoot.LayoutUpdated -= this.LayoutRoot_LayoutUpdated;

            var isMultiForm = string.IsNullOrEmpty(this.CardId);

            btn_Menu.Style =
                App.Current.Resources["ButtonMenuToggle"] as Style;
            btn_Wrap.Style = btn_RunningOnly.Style = btn_CO.Style =
                btn_Vars.Style =
                App.Current.Resources["ButtonToolBarToggle"] as Style;
            mnu_Back.Style =
            btn_Back.Style =
            btn_Forward.Style =
            mnu_Forward.Style =
            btn_Refresh.Style =
            btn_Reset.Style =
            btnClear.Style =
            btnRun.Style =
            btnFullscreen.Style =
            btn_Help.Style =
            btn_Settings.Style =
            btn_Print.Style =
            btnCopy.Style = App.Current.Resources["ButtonToolBar"] as Style;

            btn_Menu.Checked += new RoutedEventHandler(btn_Menu_Checked);
            btn_Menu.Unchecked += new RoutedEventHandler(btn_Menu_Unchecked);
            btnClear.Click += new RoutedEventHandler(btnClear_Click);
            btnCopy.Click += new RoutedEventHandler(btnCopy_Click);
            btn_Wrap.Checked += new RoutedEventHandler(chkWrap_Checked);
            btn_Wrap.Unchecked += new RoutedEventHandler(chkWrap_Unchecked);

            mnu_Back.Height = 26;
            mnu_Forward.Height = 26;

            SafeDoInit(() =>
            {
                Image imgMenu = new Image();
                imgMenu.Source = new BitmapImage(new Uri(Images1 + "Items/Images/Menu.png", UriKind.Relative));
                this.btn_Menu.Content = imgMenu;
                btn_Menu.Height = 26;
                btn_Menu.Width = 26;
                btn_Menu.Margin = new Thickness(0, 1, 1, 1);
            },
                "Menu.png");

            StackPanel tb = TabContainer.TabControl.GetControlFromTemplate("ToolBar") as StackPanel;
            if (tb != null)
            {
                m_MainToobar = new MainToolbarHolder(tb);
                tb.Children.Add(btn_Menu);

                //if (isMultiForm)
                {
                    MenuSplitter split = new MenuSplitter();
                    split.Margin = new Thickness(4, 0, 4, 0);
                    tb.Children.Add(split);
                }
                tb.Children.Add(mnu_Back);
                tb.Children.Add(btn_Back);
                tb.Children.Add(btn_Forward);
                tb.Children.Add(mnu_Forward);

                //if (isMultiForm)
                {
                    MenuSplitter split1 = new MenuSplitter();
                    split1.Margin = new Thickness(4, 0, 4, 0);
                    tb.Children.Add(split1);
                }

                // Refresh
                //
                SafeDoInit(() =>
                {
                    Image imgRefresh = new Image();
                    imgRefresh.Source = new BitmapImage(new Uri(Images1 + "Items/Images/Refresh.png", UriKind.Relative));
                    this.btn_Refresh.Content = imgRefresh;
                    btn_Refresh.Height = 26;
                    btn_Refresh.Width = 26;
                    btn_Refresh.Margin = new Thickness(1, 1, 1, 1);

                    tb.Children.Add(btn_Refresh);
                }, "Refresh.png");

                // Reset
                //
                SafeDoInit(() =>
                {
                    Image imgRecover = new Image();
                    imgRecover.Source = new BitmapImage(new Uri(Images1 + "Items/Images/Recover.png", UriKind.Relative));
                    this.btn_Reset.Content = imgRecover;
                    btn_Reset.Height = 26;
                    btn_Reset.Width = 26;
                    btn_Reset.Margin = new Thickness(1, 1, 1, 1);
                }, "Reset.png");

                tb.Children.Add(btn_Reset);

                // Run
                //
                SafeDoInit(() =>
                {
                    btnRun.Width = btnRun.Height = 26;
                    btnRun.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/Run.png", UriKind.Relative)) };
                    btnRun.Click += new RoutedEventHandler(btnRun_Click);
                    tb.Children.Add(btnRun);
                }, "Run.png");

                // Context windows
                //
                tb.Children.Add(new MenuSplitter() { Margin = new Thickness(4, 0, 4, 0) });

                SafeDoInit(() =>
                {
                    btn_CO.Width = btn_CO.Height = 26;
                    btn_CO.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/ContextWindows.png", UriKind.Relative)) };
                    //btn_CO.Click += new RoutedEventHandler(btnRun_Click);
                    tb.Children.Add(btn_CO);
                }, "ContextWindows.png");

                // Variables
                //
                SafeDoInit(() =>
                {
                    btn_Vars.Width = btn_Vars.Height = 26;
                    btn_Vars.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/Variables.png", UriKind.Relative)) };
                    //btn_CO.Click += new RoutedEventHandler(btnRun_Click);
                    tb.Children.Add(btn_Vars);
                }, "Variables.png");

                // Help
                //

                SafeDoInit(() =>
                {
                    btn_Help.Width = btn_Help.Height = 26;
                    btn_Help.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/Help.png", UriKind.Relative)) };
                    btn_Help.Click += new RoutedEventHandler(btn_Help_Click);
                    tb.Children.Add(btn_Help);

                    tb.Children.Add(new MenuSplitter() { Margin = new Thickness(4, 0, 4, 0) });
                }, "Help.png");

                // Fullscreen
                //

                SafeDoInit(() =>
                {
                    btnFullscreen.Width = btnFullscreen.Height = 26;
                    btnFullscreen.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/FullScreen16.png", UriKind.Relative)) };
                    btnFullscreen.Click += new RoutedEventHandler(btnFullscreen_Click);
                    tb.Children.Add(btnFullscreen);
                }, "FullScreen.png");

                //if (isMultiForm)
                //{
                //    MenuSplitter split2 = new MenuSplitter();
                //    split2.Margin = new Thickness(4, 0, 4, 0);
                //    tb.Children.Add(split2);
                //}

                // Print
                //
                SafeDoInit(() =>
                {
                    btn_Print.Width = btn_Print.Height = 26.0;
                    btn_Print.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/Snapshot.png", UriKind.Relative)) };
                    btn_Print.Click += new RoutedEventHandler(btn_Print_Click);
                    btn_Print.Visibility = Visibility.Collapsed;
                    tb.Children.Add(btn_Print);
                }, "Print.png");


                // Settings
                //
                SafeDoInit(() =>
                {
                    btn_Settings.Width = btn_Settings.Height = 26.0;
                    btn_Settings.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/Settings.png", UriKind.Relative)) };
                    btn_Settings.Click += new RoutedEventHandler(btn_Settings_Click);
                    tb.Children.Add(btn_Settings);
                }, "Settings.png");
            }

            btn_Back.Click += new RoutedEventHandler(btn_Back_Click);
            btn_Forward.Click += new RoutedEventHandler(btn_Forward_Click);
            btn_Refresh.Click += new RoutedEventHandler(btn_Refresh_Click);
            btn_Reset.Click += new RoutedEventHandler(btn_Reset_Click);

            // Arm menu
            //
            menuExpander = TabContainer.TabControl.GetControlFromTemplate("Menu_Expander") as VerticalExpander;
            if (menuExpander != null)
            {
                //if (isMultiForm)
                {
                    TreeView treeView = new TreeView();
                    m_ArmTreeView = treeView;
                    treeView.Style = App.Current.Resources["TreeViewGlowStyle"] as Style;
                    treeView.BorderThickness = new Thickness(0.0);
                    Border contentTab = TabContainer.TabControl.GetControlFromTemplate("ContentTab") as Border;
                    if (contentTab != null)
                    {
                        treeView.Background = contentTab.Background;
                    }
                    treeView.Items.Clear();
                    this.CreateWorkstations();
                }
            }
            mainSpl = TabContainer.TabControl.GetControlFromTemplate("MenuSplitter") as GridSplitter;

            // Инициализация панели раздела Output

            SafeDoInit(() =>
            {
                Image imgClear = new Image();
                imgClear.Source = new BitmapImage(new Uri(Images1 + "Items/Images/ClearAll.png", UriKind.Relative));
                btnClear.Content = imgClear;
                btnClear.Height = 26;
                btnClear.Width = 26;
            }, "ClearAll.png");

            SafeDoInit(() =>
            {
                Image imgCopy = new Image();
                imgCopy.Source = new BitmapImage(new Uri(Images1 + "Items/Images/Copy.png", UriKind.Relative));
                btnCopy.Content = imgCopy;
                btnCopy.Height = 26;
                btnCopy.Width = 26;
            }, "Copy.png");

            SafeDoInit(() =>
            {
                Image imgWrap = new Image();
                imgWrap.Source = new BitmapImage(new Uri(Images1 + "Items/Images/Unit.png", UriKind.Relative));
                btn_Wrap.Content = imgWrap;
                btn_Wrap.Height = 26;
                btn_Wrap.Width = 26;
            }, "Unit.png");

            SafeDoInit(() =>
            {
                btn_RunningOnly.Content = new Image() { Source = new BitmapImage(new Uri(Images1 + "Items/Images/Running.png", UriKind.Relative)) };
                btn_RunningOnly.Width = btn_RunningOnly.Height = 26.0;
                btn_RunningOnly.IsEnabled = false;
                btn_RunningOnly.Click += new RoutedEventHandler(btn_RunningOnly_Click);
            }, "Running.png");

            //chkWrap.VerticalAlignment = VerticalAlignment.Center;
            //chkWrap.Margin = new Thickness(2, 0, 5, 0);

            StackPanel toolBar = outputControl.TabOutputControl.GetControlFromTemplate("ToolBar") as StackPanel;
            if (toolBar != null)
            {
                toolBar.Children.Add(btnClear);
                toolBar.Children.Add(btnCopy);
                toolBar.Children.Add(btn_Wrap);
                toolBar.Children.Add(btn_RunningOnly);
            }

            //btn_Wrap.Content = Localization.Str_WorldWrap;
            ToolTipService.SetToolTip(btnClear, new StyledToolTip() { Content = Localization.Tooltip_ClearOutput });
            ToolTipService.SetToolTip(btnCopy, new StyledToolTip() { Content = Localization.Tooltip_CopyOutput });
            ToolTipService.SetToolTip(btn_Wrap, new StyledToolTip() { Content = Localization.Tooltip_WordWrap });
            ToolTipService.SetToolTip(btn_RunningOnly, new StyledToolTip() { Content = Localization.Tooltip_ShowOnlyExecutingProcesses });

            var p = outputControl.TabOutputControl.AddPage(Localization.Str_Output, string.Empty, outputControl.TextBoxOutput, false);
            p.Style = App.Current.Resources["TabControlOutputItem"] as Style;
            p = outputControl.TabOutputControl.AddPage(Localization.Str_Processes, string.Empty, outputControl.TaskPanel, false);
            p.Style = App.Current.Resources["TabControlOutputItem"] as Style;
            p = outputControl.TabOutputControl.AddPage(QueryExecutionViewerLocalization.Str_Queries, string.Empty, outputControl.QueryViewer, false);
            p.Style = App.Current.Resources["TabControlOutputItem"] as Style;

            outputControl.TabOutputControl.SelectionChanged += new SelectionChangedEventHandler(TabOutputControl_SelectionChanged);
            /*
            if (!isMultiForm)
            {
                btn_Back.Visibility =
                    mainSpl.Visibility = 
                    btn_Forward.Visibility =
                    mnu_Back.Visibility = 
                    mnu_Forward.Visibility =
                    btn_Menu.Visibility = Visibility.Collapsed;
                menuExpander.IsExpanded = false;

                //outputControl.TabOutputControl.
                var t = TabContainer.TabControl.GetControlFromTemplate("border") as FrameworkElement;
                if (t != null)
                {
                    t.Visibility = Visibility.Collapsed;
                }

                t = TabContainer.TabControl.GetControlFromTemplate("Menu_Expander_Border") as FrameworkElement;
                if (t != null)
                {
                    t.Visibility = Visibility.Collapsed;
                }
            }
            */
        }

        void btn_Print_Click(object sender, RoutedEventArgs e)
        {
            if (!HtmlPage.IsEnabled) return;

            //if ((this.TabContainer.TabControl.SelectedItem as TabPage) != null)
            //{
            //    var form = this.TabPageFormResolver.GetForm(this.TabContainer.TabControl.SelectedItem as TabPage);
            //    WriteableBitmap wb = new WriteableBitmap(form, new TranslateTransform());
            //    EditableImage imageData = new EditableImage(wb.PixelWidth, wb.PixelHeight);

            //    for (int y = 0; y < wb.PixelHeight; ++y)
            //    {
            //        for (int x = 0; x < wb.PixelWidth; ++x)
            //        {
            //            int pixel = wb.Pixels[wb.PixelWidth * y + x];
            //            imageData.SetPixel(x, y,
            //                               (byte)((pixel >> 16) & 0xFF),
            //                               (byte)((pixel >> 8) & 0xFF),
            //                               (byte)(pixel & 0xFF),
            //                               (byte)((pixel >> 24) & 0xFF)

            //                );
            //        }
            //    }
            //    Stream pngStream = imageData.GetStream();

            //    byte[] binaryData = new Byte[pngStream.Length];
            //    long bytesRead = pngStream.Read(binaryData, 0, (int)pngStream.Length);
            //    string fileName = null;
            //    SaveFileDialog dialog = new SaveFileDialog();
            //    try
            //    {
            //        dialog.DefaultExt = ".png";
            //        dialog.Filter = "Image Files|*.png|All Files|*.*";
            //        dialog.FilterIndex = 2;

            //        if (dialog.ShowDialog() == true)
            //        {
            //            using (var fs = dialog.OpenFile())
            //            {
            //                fs.Write(binaryData, 0, (int)bytesRead);
            //                fs.Flush();
            //            }

            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        throw new InvalidOperationException("Cannot save file!", ex);
            //    }
            //}
        }

        internal void UpdateLocalizableResources()
        {
            if (outputControl.TabOutputControl.TabPages.Count > 0)
            {
                outputControl.TabOutputControl.TabPages[0].Text = Localization.Str_Output;
                outputControl.TabOutputControl.TabPages[1].Text = Localization.Str_Processes;
                outputControl.TabOutputControl.TabPages[2].Text = QueryExecutionViewerLocalization.Str_Queries;
            }

            outputControl.QueryViewer.UpdateLocalizableResources();
            ToolTipService.SetToolTip(btnClear, new StyledToolTip() { Content = Localization.Tooltip_ClearOutput });
            ToolTipService.SetToolTip(btnCopy, new StyledToolTip() { Content = Localization.Tooltip_CopyOutput });
            ToolTipService.SetToolTip(btn_Wrap, new StyledToolTip() { Content = Localization.Tooltip_WordWrap });
            ToolTipService.SetToolTip(btn_RunningOnly, new StyledToolTip() { Content = Localization.Tooltip_ShowOnlyExecutingProcesses });

            ToolTipService.SetToolTip(btn_Back, new StyledToolTip() { Content = Localization.Str_Back });
            ToolTipService.SetToolTip(btn_Forward, new StyledToolTip() { Content = Localization.Str_Forward });
            ToolTipService.SetToolTip(btn_Menu, new StyledToolTip() { Content = Localization.Str_ShowHideWorkstationTree });
            ToolTipService.SetToolTip(btn_Refresh, new StyledToolTip() { Content = Localization.Str_Refresh });
            ToolTipService.SetToolTip(btn_Reset, new StyledToolTip() { Content = Localization.Str_Reset });
            ToolTipService.SetToolTip(btnRun, new StyledToolTip() { Content = Localization.Str_RunPendingChanges });
            ToolTipService.SetToolTip(btnFullscreen, new StyledToolTip() { Content = Localization.Tooltip_ViewInFullScreenMode });
            ToolTipService.SetToolTip(btn_Help, new StyledToolTip() { Content = Localization.Tooltip_Help });
            ToolTipService.SetToolTip(btn_CO, new StyledToolTip() { Content = Localization.Tooltip_ContextWindows });
            ToolTipService.SetToolTip(btn_Settings, new StyledToolTip() { Content = Localization.Tooltip_Settings });
            ToolTipService.SetToolTip(btn_Print, new StyledToolTip() { Content = Localization.Tooltip_Print });
            ToolTipService.SetToolTip(btn_Vars, new StyledToolTip() { Content = Localization.Tooltip_Variables });
        }

        void btn_Settings_Click(object sender, RoutedEventArgs e)
        {
            DefaultSettingOverrideForm form = new DefaultSettingOverrideForm();
            form.IsDropDownOpen = true;
            form.LoadData(App.CurrentApp.Binder.UserSettings);
            form.Closed += new EventHandler(form_Closed);
        }

        void form_Closed(object sender, EventArgs e)
        {
            DefaultSettingOverrideForm form = sender as DefaultSettingOverrideForm;
            if (form != null)
            {
                if (form.DialogResult.HasValue && form.DialogResult.Value)
                {
                    var taskMgr = App.CurrentApp.GetService<IUserTaskManager>();
                    if (taskMgr != null)
                    {
                        var settings = form.GetChangeSet();
                        taskMgr.RunTask(Localization.AppTask_UpdatingVariables, _ =>
                        {
                            ClientAppHolder.SetUserSettings(settings);
                            //using (var srv = new SyncMetaService())
                            //{
                            //    srv.SetAppItems(settings);
                            //}
                        });
                    }
                }
            }
        }

        void btn_Help_Click(object sender, RoutedEventArgs e)
        {
            //HelpManager.Show();
            ((PageNavigator)this.AppManager).ShowCurrentHelp();
        }

        //private void mnu_Back_Expanded(object sender, RoutedEventArgs e)
        //{
        //    if (this.Navigator is PageNavigator)
        //    {
        //        (this.Navigator as PageNavigator).OnMenuBack_Expanded(popup_Back, new CancelEventArgs());
        //    }
        //}        

        //private void mnu_Forward_Expanded(object sender, RoutedEventArgs e)
        //{
        //    if (this.Navigator is PageNavigator)
        //    {
        //        (this.Navigator as PageNavigator).OnMenuForward_Expanded(popup_Forward, new CancelEventArgs());
        //    }
        //}

        //private void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
        //{
        //    if (OutputPopup.IsOpen)
        //    {
        //        OutputPopup.HorizontalOffset = 5;
        //        OutputPopup.VerticalOffset = rootContainer.ActualHeight - rootContainer.ActualHeight / 3;
        //        GridOutput.Width = rootContainer.ActualWidth - 10;
        //        GridOutput.Height = rootContainer.ActualHeight / 3 - 30;
        //    }
        //}
    }
}
